{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Matplotlib　[官网](https://matplotlib.org/users/pyplot_tutorial.html)\n",
    "\n",
    "Matplotlib的设计理念是能够用轻松简单的方式生成强大的可视化效果，是Python学习过程中核心库之一。\n",
    "\n",
    "用在python中绘制数组的2D图形库\n",
    "\n",
    "matplotlib代码在概念上分为3个部分：\n",
    "\n",
    "1.pylab接口是由matplotlib.pylab提供的函数集，允许用户使用非常类似于MATLAB图生成代码的代码创建绘图\n",
    "\n",
    "2.matplotlib前端或API是一组重要的类，可创建和管理图形，文本，线条，图表等（艺术家教程），是一个对输出无所了解的抽象接口\n",
    "\n",
    "3.后端是设备相关的绘图设备，也称为渲染器，将前端表示转换为打印件或显示设备；后端示例：PS 创建 PostScript® 打印件，SVG 创建可缩放矢量图形打印件，Agg 使用 Matplotlib 附带的高质量反颗粒几何库创建 PNG 输出，GTK 在 Gtk+ 应用程序中嵌入 Matplotlib，GTKAgg 使用反颗粒渲染器创建图形并将其嵌入到 Gtk+ 应用程序中，以及用于 PDF，WxWidgets，Tkinter 等\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib\n",
    "import matplotlib.mlab as mlab\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 例子１\n",
    "\n",
    "def simple_plot():\n",
    "    # 生成测试数据\n",
    "    x = np.linspace(-np.pi, np.pi, 256, endpoint=True)\n",
    "    y_cos, y_sin = np.cos(x), np.sin(x)\n",
    "\n",
    "    # 生成画布，并设定标题\n",
    "    # 画布大小，dpi＝清晰度\n",
    "    plt.figure(figsize=(8, 6), dpi=80)\n",
    "    plt.title(\"Simple plot\")\n",
    "    plt.grid(True)  # 带网格\n",
    "\n",
    "    # 设置X轴\n",
    "    plt.xlabel(\"X\")\n",
    "    plt.xlim(-4.0, 4.0)\n",
    "    plt.xticks(np.linspace(-4, 4, 9, endpoint=True))\n",
    "\n",
    "    # 设置Y轴\n",
    "    plt.ylabel(\"Y\")\n",
    "    plt.ylim(-1.0, 1.0)\n",
    "    plt.yticks(np.linspace(-1, 1, 9, endpoint=True))\n",
    "\n",
    "    # 画两条曲线\n",
    "    plt.plot(x, y_cos, \"b--\", linewidth=2.0, label=\"cos\")\n",
    "    plt.plot(x, y_sin, \"g-\", linewidth=2.0, label=\"sin\")\n",
    "\n",
    "    # 设置图例位置,loc可以为[upper, lower, left, right, center]\n",
    "    plt.legend(loc=\"upper left\",shadow=True) \n",
    "\n",
    "    # 图形显示\n",
    "    plt.show()\n",
    "    return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "simple_plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 更复杂一点\n",
    "def simple_advanced_plot():\n",
    "    \"\"\"\n",
    "    simple advanced plot\n",
    "    \"\"\"\n",
    "    # 生成测试数据\n",
    "    x = np.linspace(-np.pi, np.pi, 256, endpoint=True)\n",
    "    y_cos, y_sin = np.cos(x), np.sin(x)\n",
    "\n",
    "    # 生成画布, 并设定标题\n",
    "    plt.figure(figsize=(8, 6), dpi=80)\n",
    "    plt.title(\"simple advanced plot\")\n",
    "    plt.grid(True)\n",
    "\n",
    "    # 画图的另外一种方式\n",
    "    ax_1 = plt.subplot(111) # 也可以写成plt.subplot(1,1,1)\n",
    "    ax_1.plot(x, y_cos, color=\"blue\", linewidth=2.0, linestyle=\"--\", label=\"left cos\")\n",
    "    ax_1.legend(loc=\"upper left\", shadow=True)\n",
    "\n",
    "    # 设置Y轴(左边)\n",
    "    ax_1.set_ylabel(\"left cos y\")\n",
    "    ax_1.set_ylim(-1.0, 1.0)\n",
    "    ax_1.set_yticks(np.linspace(-1, 1, 9, endpoint=True))\n",
    "\n",
    "    # 画图的另外一种方式\n",
    "    ax_2 = ax_1.twinx()\n",
    "    ax_2.plot(x, y_sin, color=\"green\", linewidth=2.0, linestyle=\"-\", label=\"right sin\")\n",
    "    ax_2.legend(loc=\"upper right\", shadow=True)\n",
    "\n",
    "    # 设置Y轴(右边)\n",
    "    ax_2.set_ylabel(\"right sin y\")\n",
    "    ax_2.set_ylim(-2.0, 2.0)\n",
    "    ax_2.set_yticks(np.linspace(-2, 2, 9, endpoint=True))\n",
    "\n",
    "    # 设置X轴(共同)\n",
    "    ax_1.set_xlabel(\"x\")\n",
    "    ax_1.set_xlim(-4.0, 4.0)\n",
    "    ax_1.set_xticks(np.linspace(-4, 4, 9, endpoint=True))\n",
    "\n",
    "    # 图形显示\n",
    "    plt.show()\n",
    "    return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "simple_advanced_plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 练习把上面的图，改一下线段颜色和形式， 如：red, yellow, ; -."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 一次画多个图\n",
    "def subplot_plot():\n",
    "    \"\"\"\n",
    "    subplot plot\n",
    "    \"\"\"\n",
    "    # 子图的style列表\n",
    "    style_list = [\"g+-\", \"r*-\", \"b.-\", \"yo-\"]\n",
    "    \n",
    "    plt.figure(figsize=(8, 6), dpi=80)\n",
    "\n",
    "    # 依次画图\n",
    "    for num in range(4):\n",
    "        # 生成测试数据\n",
    "        x = np.linspace(0.0, 2+num, num=10*(num+1))\n",
    "        y = np.sin((5-num) * np.pi * x)\n",
    "\n",
    "        # 子图的生成方式\n",
    "        plt.subplot(2, 2, num+1)\n",
    "        plt.title(\"sub plot %d\" % (num+1))\n",
    "        plt.plot(x, y, style_list[num])\n",
    "\n",
    "    # 图形显示\n",
    "    plt.show()\n",
    "    return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "subplot_plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 柱状图\n",
    "def bar_plot():\n",
    "    \"\"\"\n",
    "    bar plot\n",
    "    \"\"\"\n",
    "    # 生成测试数据\n",
    "    means_men = (20, 35, 30, 35, 27)\n",
    "    means_women = (25, 32, 34, 20, 25)\n",
    "\n",
    "    # 设置标题\n",
    "    plt.title(\"bar plot\")\n",
    "\n",
    "    # 设置相关参数\n",
    "    index = np.arange(len(means_men))\n",
    "    bar_width = 0.35\n",
    "\n",
    "    # 画柱状图\n",
    "    plt.bar(index, means_men, width=bar_width, alpha=0.2, color=\"b\", label=\"boy\")\n",
    "    plt.bar(index+bar_width, means_women, width=bar_width, alpha=0.8, color=\"r\", label=\"lady\")\n",
    "    plt.legend(loc=\"upper right\",shadow=True)\n",
    "\n",
    "    # 设置柱状图标示\n",
    "    for x, y in zip(index, means_men):\n",
    "        plt.text(x, y+0.3, y, ha=\"center\", va=\"bottom\")\n",
    "    for x, y in zip(index, means_women):\n",
    "        plt.text(x+bar_width, y+0.3, y, ha=\"center\", va=\"bottom\")\n",
    "\n",
    "    # 设置刻度范围/坐标轴名称等\n",
    "    plt.ylim(0, 45)\n",
    "    plt.xlabel(\"Group\")\n",
    "    plt.ylabel(\"Scores\")\n",
    "    plt.xticks(index+(bar_width/2), (\"A\", \"B\", \"C\", \"D\", \"E\"))\n",
    "\n",
    "    # 图形显示\n",
    "    plt.show()\n",
    "    return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bar_plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 横向柱状图\n",
    "def barh_plot():\n",
    "    \"\"\"\n",
    "    barh plot\n",
    "    \"\"\"\n",
    "    # 生成测试数据\n",
    "    means_men = (20, 35, 30, 35, 27)\n",
    "    means_women = (25, 32, 34, 20, 25)\n",
    "\n",
    "    # 设置标题\n",
    "    plt.title(\"barh plot\")\n",
    "\n",
    "    # 设置相关参数\n",
    "    index = np.arange(len(means_men))\n",
    "    bar_height = 0.35\n",
    "\n",
    "    # 画柱状图(水平方向)\n",
    "    plt.barh(index, means_men, height=bar_height, alpha=0.2, color=\"b\", label=\"Men\")\n",
    "    plt.barh(index+bar_height, means_women, height=bar_height, alpha=0.8, color=\"r\", label=\"Women\")\n",
    "    plt.legend(loc=\"upper right\", shadow=True)\n",
    "\n",
    "    # 设置柱状图标示\n",
    "    for x, y in zip(index, means_men):\n",
    "        plt.text(y+0.3, x, y, ha=\"left\", va=\"center\")\n",
    "    for x, y in zip(index, means_women):\n",
    "        plt.text(y+0.3, x+bar_height, y, ha=\"left\", va=\"center\")\n",
    "\n",
    "    # 设置刻度范围/坐标轴名称等\n",
    "    plt.xlim(0, 45)\n",
    "    plt.xlabel(\"Scores\")\n",
    "    plt.ylabel(\"Group\")\n",
    "    plt.yticks(index+(bar_height/2), (\"A\", \"B\", \"C\", \"D\", \"E\"))\n",
    "\n",
    "    # 图形显示\n",
    "    plt.show()\n",
    "    return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "barh_plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 层次柱状图\n",
    "def table_plot():\n",
    "    \"\"\"\n",
    "    table plot\n",
    "    \"\"\"\n",
    "    # 生成测试数据\n",
    "    data = np.array([\n",
    "        [1, 4, 2, 5, 2],\n",
    "        [2, 1, 1, 3, 6],\n",
    "        [5, 3, 6, 4, 1]\n",
    "    ])\n",
    "\n",
    "    # 设置标题\n",
    "    plt.title(\"table plot\")\n",
    "\n",
    "    # 设置相关参数\n",
    "    index = np.arange(len(data[0]))\n",
    "    color_index = [\"r\", \"g\", \"b\"]\n",
    "\n",
    "    # 声明底部位置\n",
    "    bottom = np.array([0, 0, 0, 0, 0])\n",
    "\n",
    "    # 依次画图,并更新底部位置\n",
    "    for i in range(len(data)):\n",
    "        plt.bar(index, data[i], width=0.5, color=color_index[i], bottom=bottom, alpha=0.7, label=\"label %d\" % i)\n",
    "        bottom += data[i]\n",
    "\n",
    "    # 设置图例位置\n",
    "    plt.legend(loc=\"upper left\", shadow=True)\n",
    "\n",
    "    # 图形显示\n",
    "    plt.show()\n",
    "    return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "table_plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 饼图\n",
    "def pie_plot():\n",
    "    \"\"\"\n",
    "    pie plot\n",
    "    \"\"\"\n",
    "    # 生成测试数据\n",
    "    sizes = [15, 30, 45, 10]\n",
    "    labels = [\"Frogs\", \"Cat\", \"Dogs\", \"Logs\"]\n",
    "    colors = [\"yellowgreen\", \"gold\", \"lightskyblue\", \"lightcoral\"]\n",
    "\n",
    "    # 设置标题\n",
    "    plt.title(\"pie\")\n",
    "\n",
    "    # 设置突出参数\n",
    "    explode = [0, 0.05, 0, 0]\n",
    "\n",
    "    # 画饼状图\n",
    "    patches, l_text, p_text = plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct=\"%1.1f%%\", shadow=True, startangle=90)\n",
    "\n",
    "    plt.axis(\"equal\")\n",
    "\n",
    "    # 图形显示\n",
    "    plt.show()\n",
    "    return\n",
    "# pie_plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pie_plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 散点图\n",
    "def scatter_plot():\n",
    "    \"\"\"\n",
    "    scatter plot\n",
    "    \"\"\"\n",
    "    # 生成测试数据\n",
    "    point_count = 1000\n",
    "    x_index = np.random.random(point_count)\n",
    "    y_index = np.random.random(point_count)\n",
    "\n",
    "    # 设置标题\n",
    "    plt.title(\"scatter\")\n",
    "\n",
    "    # 设置相关参数\n",
    "    color_list = np.random.random(point_count)\n",
    "    scale_list = np.random.random(point_count) * 100\n",
    "\n",
    "    # 画散点图\n",
    "    plt.scatter(x_index, y_index, s=scale_list, c=color_list, marker=\"o\")\n",
    "\n",
    "    # 图形显示\n",
    "    plt.show()\n",
    "    return\n",
    "# scatter_plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scatter_plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 雷达图\n",
    "def radar_plot():\n",
    "    \"\"\"\n",
    "    radar plot\n",
    "    \"\"\"\n",
    "    # 生成测试数据\n",
    "    labels = np.array([\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"])\n",
    "    data = np.array([68, 83, 90, 77, 89, 73])\n",
    "    theta = np.linspace(0, 2*np.pi, len(data), endpoint=False)\n",
    "\n",
    "    # 数据预处理\n",
    "    data = np.concatenate((data, [data[0]]))\n",
    "    theta = np.concatenate((theta, [theta[0]]))\n",
    "\n",
    "    # 画图方式\n",
    "    plt.subplot(111, polar=True)\n",
    "    plt.title(\"radar\")\n",
    "\n",
    "    # 设置\"theta grid\"/\"radar grid\"\n",
    "    plt.thetagrids(theta*(180/np.pi), labels=labels)\n",
    "    plt.rgrids(np.arange(20, 100, 20), labels=np.arange(20, 100, 20), angle=0)\n",
    "    plt.ylim(0, 100)\n",
    "\n",
    "    # 画雷达图,并填充雷达图内部区域\n",
    "    plt.plot(theta, data, \"bo-\", linewidth=2)\n",
    "    plt.fill(theta, data, color=\"red\", alpha=0.25)\n",
    "    \n",
    "    # 保存图片\n",
    "    plt.savefig('radar.png')\n",
    "    # 图形显示\n",
    "    plt.show()\n",
    "    return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "radar_plot()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 练习\n",
    "# 测试数据，5次考试的平均值， 第一行是1班考试成绩，第二行是2班考试成绩， 自定义一个主题，画一个柱状图， 画一个饼图， 如1班和2班5次成绩比较， \n",
    "data = np.array([\n",
    "    [80, 84, 92, 100, 62],\n",
    "    [60, 100, 100, 93, 86],\n",
    "])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pandas 中的使用\n",
    "\n",
    "[参数说明](https://blog.csdn.net/claroja/article/details/73872066?utm_source=debugrun&utm_medium=referral)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(0,2*np.pi,100)          # 从0 到 2π  取100份\n",
    "df = pd.DataFrame(data={'sin':np.sin(x),'cos':np.cos(x)},index=x)   #创建DataFrame对象\n",
    "df.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.plot(title='title', fontsize=20, figsize=(8, 6), grid=True)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = pd.Series(data=np.random.randint(0,10,size=5),index=list('abcde'))  \n",
    "s.plot(kind='barh')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame(np.random.randint(0,150,size=(20,3)),columns=['python','math','eng'])\n",
    "df.plot(kind='scatter',x='python',y='eng')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df['php'] = df['python'].map(lambda x: x*0.9+np.random.randint(-10,10,1)[0])\n",
    "df.plot(kind='scatter',x='python',y='php')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 练习 录入数据， 用id 和 price 两个参数画一个柱状图 , 散点图\n",
    "wz_df = pd.read_csv('datas/waizi_v2.csv')\n",
    "wz_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "wz_df = wz_df[wz_df['type']=='合同外资金额']\n",
    "wz_df.plot(kind='???',x='???',y='???')\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
